package com.enzoism.springboot.dive.service;

import com.enzoism.springboot.dive.tx.DataSourceConnectHolder;
import com.enzoism.springboot.dive.tx.MyTransaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

@Service
public class MyTransactionService {

    @Autowired
    private DataSourceConnectHolder holder;

    // 一个事务中执行两个sql插入
//    @MyTransaction(rollbackFor = NullPointerException.class)
    @MyTransaction(rollbackFor = Exception.class)
    public void saveTest(int id) {
        save(id, "白菜Java自习室");
        save(id + 10, "白菜Java自习室");
        throw new RuntimeException();
    }

    // 执行sql
    private void save(int id, String value) {
        String sql = "insert into test_tx values(?,?)";
        Connection connection = holder.getConnection();
        PreparedStatement stmt = null;
        try {
            stmt = connection.prepareStatement(sql);
            stmt.setInt(1, id);
            stmt.setString(2, value);
            stmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}